package com.chanven.lib.cptr;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.graphics.drawable.AnimationDrawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.chanven.lib.cptr.header.HeaderChangeInterface;
import com.chanven.lib.cptr.indicator.PtrIndicator;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class PtrClassicDefaultHeader extends FrameLayout implements PtrUIHandler {

    private final static String KEY_SharedPreferences = "cube_ptr_classic_last_update";
    private static SimpleDateFormat sDataFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    //    private int mRotateAniTime = 150;
//    private RotateAnimation mFlipAnimation;
//    private RotateAnimation mReverseFlipAnimation;
    private Context mContext;
    private TextView mTitleTextView;
    private ImageView mRotateView;
    private ImageView mRotateAnView;
    //private FrameLayout mRotateFrame;
    //private View mProgressBar;
    private long mLastUpdateTime = -1;
    private TextView mLastUpdateTextView;
    private String mLastUpdateTimeKey;
    private boolean mShouldShowLastUpdate;
    //private Matrix mHeaderImageMatrix;
    private AnimationDrawable animationDrawable;

    private LastUpdateTimeUpdater mLastUpdateTimeUpdater = new LastUpdateTimeUpdater();

    private boolean isWhiteTheme;

    public PtrClassicDefaultHeader(Context context) {
        super(context);
        initViews(context, null);
    }

    public PtrClassicDefaultHeader(Context context, AttributeSet attrs) {
        super(context, attrs);
        initViews(context, attrs);
    }

    public PtrClassicDefaultHeader(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initViews(context, attrs);
    }

    protected void initViews(Context context, AttributeSet attrs) {
        this.mContext = context;
        TypedArray arr = getContext().obtainStyledAttributes(attrs, com.chanven.lib.cptr.R.styleable.PtrClassicHeader, 0, 0);
        if (arr != null) {
            //mRotateAniTime = arr.getInt(com.chanven.lib.cptr.R.styleable.PtrClassicHeader_ptr_rotate_ani_time, mRotateAniTime);
            arr.recycle();
        }
        //buildAnimation();
        View header = LayoutInflater.from(getContext()).inflate(com.chanven.lib.cptr.R.layout.cube_ptr_classic_default_header, this);

        mRotateView = (ImageView) header.findViewById(R.id.ptr_classic_header_rotate_view);
        //mRotateFrame = (FrameLayout) header.findViewById(R.id.ptr_classic_header_rotate_view_header_img);
        mRotateAnView = (ImageView) header.findViewById(R.id.ptr_classic_header_rotate_an_view);
        mRotateAnView.setImageResource(R.drawable.li_refresh_loading_roate);
        animationDrawable = (AnimationDrawable) mRotateAnView.getDrawable();

        mTitleTextView = (TextView) header.findViewById(com.chanven.lib.cptr.R.id.ptr_classic_header_rotate_view_header_title);
        mLastUpdateTextView = (TextView) header.findViewById(com.chanven.lib.cptr.R.id.ptr_classic_header_rotate_view_header_last_update);
        //mProgressBar = header.findViewById(com.chanven.lib.cptr.R.id.ptr_classic_header_rotate_view_progressbar);

        resetView();
    }

//    public void setRotateAniTime(int time) {
//        if (time == mRotateAniTime || time == 0) {
//            return;
//        }
//        mRotateAniTime = time;
//        buildAnimation();
//    }

    /**
     * Specify the last update time by this key string
     *
     * @param key
     */
    public void setLastUpdateTimeKey(String key) {
        if (TextUtils.isEmpty(key)) {
            return;
        }
        mLastUpdateTimeKey = key;
    }

    /**
     * Using an object to specify the last update time.
     *
     * @param object
     */
    public void setLastUpdateTimeRelateObject(Object object) {
        setLastUpdateTimeKey(object.getClass().getName());
    }

    private void resetView() {
        hideRotateView();
        //mProgressBar.setVisibility(INVISIBLE);
        mRotateAnView.setVisibility(INVISIBLE);
        animationDrawable.stop();
    }

    private void hideRotateView() {
        mRotateView.setVisibility(INVISIBLE);
    }

    private void showNonelyText(){
        //mRotateFrame.setVisibility(GONE);
        mRotateAnView.setVisibility(GONE);
        animationDrawable.stop();
        mRotateView.setVisibility(GONE);
    }

    @Override
    public void onUIReset(PtrFrameLayout frame) {
        resetView();
        mShouldShowLastUpdate = true;
        tryUpdateLastUpdateTime();
        if(headerChangeInterface != null){
            headerChangeInterface.onUIReset();
        }
        Log.e("PtrClassicDefaultHeader","onUIReset");
    }

    @Override
    public void onUIRefreshPrepare(PtrFrameLayout frame) {
        //mRotateFrame.setVisibility(VISIBLE);
        mShouldShowLastUpdate = true;
        tryUpdateLastUpdateTime();
        mLastUpdateTimeUpdater.start();

        //mProgressBar.setVisibility(INVISIBLE);
        mRotateAnView.setVisibility(INVISIBLE);
        animationDrawable.stop();

        mRotateView.setVisibility(VISIBLE);
        mTitleTextView.setVisibility(GONE);
//        if (frame.isPullToRefresh()) {
//            mTitleTextView.setText(getResources().getString(com.chanven.lib.cptr.R.string.cube_ptr_pull_down_to_refresh));
//        } else {
//            mTitleTextView.setText(getResources().getString(com.chanven.lib.cptr.R.string.cube_ptr_pull_down));
//        }
    }

    @Override
    public void onUIRefreshBegin(PtrFrameLayout frame) {
        mShouldShowLastUpdate = false;
        hideRotateView();
        //mProgressBar.setVisibility(VISIBLE);
        mRotateAnView.setVisibility(VISIBLE);
        animationDrawable.start();
//        mTitleTextView.setVisibility(VISIBLE);
//        mTitleTextView.setText(com.chanven.lib.cptr.R.string.cube_ptr_refreshing);

        tryUpdateLastUpdateTime();
        mLastUpdateTimeUpdater.stop();
        if(headerChangeInterface != null){
            headerChangeInterface.onUIRefreshBegin();
        }
    }

    @Override
    public void onUIRefreshComplete(PtrFrameLayout frame) {

        hideRotateView();
        //mProgressBar.setVisibility(INVISIBLE);
        mRotateAnView.setVisibility(INVISIBLE);
        animationDrawable.stop();
 //       mRotateView.setVisibility(VISIBLE);
//        mTitleTextView.setVisibility(VISIBLE);
//        mTitleTextView.setText(getResources().getString(com.chanven.lib.cptr.R.string.cube_ptr_refresh_complete));

        // update last update time
        SharedPreferences sharedPreferences = getContext().getSharedPreferences(KEY_SharedPreferences, 0);
        if (!TextUtils.isEmpty(mLastUpdateTimeKey)) {
            mLastUpdateTime = new Date().getTime();
            sharedPreferences.edit().putLong(mLastUpdateTimeKey, mLastUpdateTime).apply();
        }

        if(headerChangeInterface != null){
            headerChangeInterface.onUIRefreshComplete();
        }
    }

    public void onBeforeUIRefreshComplete() {
        showNonelyText();
//        //mProgressBar.setVisibility(INVISIBLE);
//        mRotateAnView.setVisibility(INVISIBLE);
//        animationDrawable.stop();
        mTitleTextView.setVisibility(VISIBLE);
        mTitleTextView.setText(getResources().getString(com.chanven.lib.cptr.R.string.cube_ptr_refresh_complete));
    }

    private void tryUpdateLastUpdateTime() {
        if (TextUtils.isEmpty(mLastUpdateTimeKey) || !mShouldShowLastUpdate) {
            mLastUpdateTextView.setVisibility(GONE);
        } else {
            String time = getLastUpdateTime();
            if (TextUtils.isEmpty(time)) {
                mLastUpdateTextView.setVisibility(GONE);
            } else {
                mLastUpdateTextView.setVisibility(VISIBLE);
                mLastUpdateTextView.setText(time);
            }
        }
    }

    private String getLastUpdateTime() {

        if (mLastUpdateTime == -1 && !TextUtils.isEmpty(mLastUpdateTimeKey)) {
            mLastUpdateTime = getContext().getSharedPreferences(KEY_SharedPreferences, 0).getLong(mLastUpdateTimeKey, -1);
        }
        if (mLastUpdateTime == -1) {
            return null;
        }
        long diffTime = new Date().getTime() - mLastUpdateTime;
        int seconds = (int) (diffTime / 1000);
        if (diffTime < 0) {
            return null;
        }
        if (seconds <= 0) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        sb.append(getContext().getString(com.chanven.lib.cptr.R.string.cube_ptr_last_update));

        if (seconds < 60) {
            sb.append(seconds + getContext().getString(com.chanven.lib.cptr.R.string.cube_ptr_seconds_ago));
        } else {
            int minutes = (seconds / 60);
            if (minutes > 60) {
                int hours = minutes / 60;
                if (hours > 24) {
                    Date date = new Date(mLastUpdateTime);
                    sb.append(sDataFormat.format(date));
                } else {
                    sb.append(hours + getContext().getString(com.chanven.lib.cptr.R.string.cube_ptr_hours_ago));
                }

            } else {
                sb.append(minutes + getContext().getString(com.chanven.lib.cptr.R.string.cube_ptr_minutes_ago));
            }
        }
        return sb.toString();
    }

    @Override
    public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {

        int mOffsetToRefresh = frame.getOffsetToRefresh();
        int currentPos = ptrIndicator.getCurrentPosY();
        int lastPos = ptrIndicator.getLastPosY();
//        if(currentPos < 40){
//            currentPos = 0;
//        }else{
//            currentPos = currentPos - 40;
//        }
        float angle = (((float)currentPos) / mOffsetToRefresh) * 100;
        int index = (int) (angle / 3);
        int maxIndex = 33;
        if (index < maxIndex) {
            if(isWhiteTheme){
                mRotateView.setImageResource(getResource("refresh_pull_roate_w_" + (index + 1)));
            }else {
                mRotateView.setImageResource(getResource("refresh_pull_roate" + (index + 1)));
            }
        } else {
            if(isWhiteTheme){
                mRotateView.setImageResource(getResource("refresh_pull_roate_w_33"));
            }else {
                mRotateView.setImageResource(getResource("refresh_pull_roate33"));
            }

        }

        if(headerChangeInterface != null){
            headerChangeInterface.headerChange(index, maxIndex);
        }
//        float mRotationPivotX = 0.0f;
//        float mRotationPivotY = 0.0f;
//        Drawable imageDrawable = mRotateView.getDrawable();
//        if(imageDrawable != null) {
//            mRotationPivotX = Math.round(imageDrawable.getIntrinsicWidth() / 2f);
//            mRotationPivotY = Math.round(imageDrawable.getIntrinsicHeight() / 2f);
//        }

//        mHeaderImageMatrix.setRotate(angle,mRotationPivotX,mRotationPivotY);
//        mRotateView.setImageMatrix(mHeaderImageMatrix);
    }

    private void crossRotateLineFromTopUnderTouch(PtrFrameLayout frame) {
        if (!frame.isPullToRefresh()) {
            mTitleTextView.setVisibility(VISIBLE);
            mTitleTextView.setText(com.chanven.lib.cptr.R.string.cube_ptr_release_to_refresh);
        }
    }

    private void crossRotateLineFromBottomUnderTouch(PtrFrameLayout frame) {
        mTitleTextView.setVisibility(VISIBLE);
        if (frame.isPullToRefresh()) {
            mTitleTextView.setText(getResources().getString(com.chanven.lib.cptr.R.string.cube_ptr_pull_down_to_refresh));
        } else {
            mTitleTextView.setText(getResources().getString(com.chanven.lib.cptr.R.string.cube_ptr_pull_down));
        }
    }

    private class LastUpdateTimeUpdater implements Runnable {

        private boolean mRunning = false;

        private void start() {
            if (TextUtils.isEmpty(mLastUpdateTimeKey)) {
                return;
            }
            mRunning = true;
            run();
        }

        private void stop() {
            mRunning = false;
            removeCallbacks(this);
        }

        @Override
        public void run() {
            tryUpdateLastUpdateTime();
            if (mRunning) {
                postDelayed(this, 1000);
            }
        }
    }

    public int getResource(String imageName) {
        int resId = getResources().getIdentifier(imageName, "drawable", mContext.getPackageName());
        return resId;
    }

    public HeaderChangeInterface getHeaderChangeInterface() {
        return headerChangeInterface;
    }

    public void setHeaderChangeInterface(HeaderChangeInterface headerChangeInterface) {
        this.headerChangeInterface = headerChangeInterface;
    }

    private HeaderChangeInterface headerChangeInterface;

    public void setWhiteTheme(boolean whiteTheme) {
        isWhiteTheme = whiteTheme;
        if(isWhiteTheme) {
            mRotateView.setImageResource(R.drawable.refresh_pull_roate_w_1);
            mRotateAnView.setImageResource(R.drawable.li_refresh_loading_roate_w);
            animationDrawable = (AnimationDrawable) mRotateAnView.getDrawable();
        }else{
            mRotateView.setImageResource(R.drawable.refresh_pull_roate1);
            mRotateAnView.setImageResource(R.drawable.li_refresh_loading_roate);
            animationDrawable = (AnimationDrawable) mRotateAnView.getDrawable();
        }
    }
}
